//官网 https://www.npmjs.com/package/express
//导包
const express = require("express")
const app = express()
var arr = []
//mysql 官网 https://www.npmjs.com/package/mysql
// var mysql = require('mysql');
// var connection = mysql.createConnection({
//     host: 'localhost',
//     user: 'root',
//     password: 'root',
//     database: 'mymanager'
// });

// connection.connect();

// connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
//     if (error) throw error;
//     console.log('The solution is: ', results[0].solution);
// });

// connection.end();

//抓包 官网https://www.npmjs.com/package/crawler
var Crawler = require("crawler");

//创建爬虫实例
var c = new Crawler({
    maxConnections: 10,
    // This will be called for each crawled page
    callback: function (error, res, done) {
        if (error) {
            console.log(error);
        } else {
            var $ = res.$;
            // $ is Cheerio by default
            //a lean implementation of core jQuery designed specifically for the server
            // console.log($("title").text());
            // console.log(JSON.parse(res.body));
            JSON.parse(res.body).forEach((v) => {
                //重新发送爬虫爬链接 
                xq.queue(`https://pvp.qq.com/web201605/herodetail/${v.ename}.shtml`);
            })

        }
        done();
    }
});


c.queue('https://pvp.qq.com/web201605/js/herolist.json');

//再创建一个爬虫实例，xq 
var xq = new Crawler({
    maxConnections: 10,
    callback: function (error, res, done) {
        if (error) {
            console.log(error);
        } else {
            var $ = res.$;
            // console.log($("title").text());

            arr.push({ heroName: $(".cover-name").text(), heroSkill: $(".skill-name>b").eq(3).text(), heroIcon: `http:` + $(".ico-play").prev().attr("src"), isDelete: 'false' })
        }
        done();
    }
});

//入库
//数据库依赖性 官网https://www.npmjs.com/package/mysql-ithm
//1.导入模块
const hm = require('mysql-ithm');

//2.连接数据库
//如果数据库存在则连接，不存在则会自动创建数据库
hm.connect({
    host: 'localhost',//数据库地址
    port: '3306',
    user: 'root',//用户名，没有可不填
    password: 'root',//密码，没有可不填
    database: 'cqmanager661'//数据库名称
});

//3.创建Model(表格模型：负责增删改查)
//如果table表格存在则连接，不存在则自动创建
let heroModel = hm.model('cqhero', {
    heroName: String,
    heroSkill: String,
    heroIcon: String,
    isDelete: String
});

//4.调用API：添加数据

xq.on('drain', function () {
    heroModel.insert(arr, (err, results) => {
        console.log(err);
        console.log(results);
        if (!err) console.log('增加成功');
    });
});




//配置接口
app.get("/", (req, res) => {
    res.send('你好啊')
})





//创建服务器
app.listen(8089, () => {
    console.log('服务器已开，端口8089');
})